package com.example.petmall.seckill.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.example.petmall.seckill.constant.SeckillConstant;
import com.example.petmall.seckill.feign.CouponFeignService;
import com.example.petmall.seckill.feign.ProductFeignService;
import com.example.petmall.seckill.interceport.LoginUserInterceptor;
import com.example.petmall.seckill.service.SeckillService;
import com.example.petmall.seckill.to.SecKillRedisTo;
import com.example.petmall.seckill.vo.SeckillSessionSkuVo;
import com.example.petmall.seckill.vo.SeckillSkuVo;
import com.example.petmall.seckill.vo.SkuInfoVo;
import com.qianji.common.exception.RabbitEnum;
import com.qianji.common.to.MemberResponseVo;
import com.qianji.common.to.seckill.SeckillCartTo;
import com.qianji.common.utils.R;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author liang zai
 * @date 2022/5/23 18:12
 * @description
 */
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;
    
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //限流返回的数据
    public List<SecKillRedisTo> getCurrentSeckillSkusFallback(){
        return null;
    }
    //获取当前可以参与秒杀的商品信息
    @Override
    //设置sentinel限流之后的处理
    //Sentinel 支持通过 @SentinelResource 注解定义资源并配置 blockHandler 和 fallback 函数来进行限流之后的处理
    @SentinelResource(value = "getCurrentSeckillSkus",fallback = "getCurrentSeckillSkusFallback")
    public List<SecKillRedisTo> getCurrentSeckillSkus() {
        //找出所有的 seckill:session:1653501600000_1653505200000 信息
        //keys 匹配redis中以seckill:session:为前缀的信息
        Set<String> keys = redisTemplate.keys(SeckillConstant.SESSION_CACHE_PREFIX + "*");
        long time = System.currentTimeMillis();
        List<SecKillRedisTo> collect = new ArrayList<>();
        for (String key : keys) {
            //替换得到1653501600000_1653505200000 信息
            String replace = key.replace(SeckillConstant.SESSION_CACHE_PREFIX, "");
            //分割得到1653501600000  1653505200000开始和结束的时间
            String[] s = replace.split("_");
            long start = Long.parseLong(s[0]);
            long end = Long.parseLong(s[1]);
            //查看当前的时间是否处于商品秒杀活动时间中的
            if (time>=start && time<=end){
                //说明当前商品处于秒杀活动的时间，获取当前商品的活动信息
                List<String> range = redisTemplate.opsForList().range(key, 0, -1);
                BoundHashOperations<String, String, String> ops =
                        redisTemplate.boundHashOps(SeckillConstant.SESSION_CACHE_SKUS);
                //通过活动信息的skuid获得所有的商品信息
                List<String> items = ops.multiGet(range);
                //找到当前时间的一场秒杀活动
                if (items!=null && items.size()>=0){
                    List<SecKillRedisTo> tos = items.stream().map(item -> {
                        SecKillRedisTo redisTo = JSON.parseObject(item, SecKillRedisTo.class);
                        collect.add(redisTo);
                        return redisTo;
                    }).collect(Collectors.toList());
                }
            }
        }
        return collect;
    }

    /**
     * 秒杀功能：流程
     *
     * 1. 判断登录 拦截器校验
     * 2. 校验参数的合法性
     *  2.1 秒杀时间校验
     *  2.2 随机码校验
     *  2.3 对应关系校验
     *  2.4 幂等性校验
     * 3. 获取分布式信号量进行扣减
     * 4. 快速创建秒杀单，用户，订单号，商品  （发送MQ）
     * 5. 收货地址填写，
     * 6. 确认支付
     */
    @Transactional
    @Override
    public String addSeckillCart(String seckillId, String key, Integer num){
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SeckillConstant.SESSION_CACHE_SKUS);
        //获取redis中的数据
        String s = ops.get(seckillId);
        SecKillRedisTo redisTo = JSON.parseObject(s, SecKillRedisTo.class);
        String sessionId =redisTo.getSkuId()+"_"+redisTo.getPromotionSessionId();
        //对比键是否相同
        //对比是否在秒杀活动时间内的
        long endTime = redisTo.getEndTime().getTime();
        long startTime = redisTo.getStartTime().getTime();
        long thisTime = System.currentTimeMillis();
        long time = endTime - startTime;
        //判断code码是否相同
        String randomCode = redisTo.getRandomCode();
        //判断当前用户是否超出了限购的数量
        int seckillLimit = redisTo.getSeckillLimit().intValue();
        //结合判断
        boolean b = !sessionId.equals(seckillId) && !randomCode.equals(key) && thisTime < startTime && thisTime > endTime && num > seckillLimit;
        if (b){
            return null;
        }
        //判断当前用户是否购买过
        MemberResponseVo responseVo = LoginUserInterceptor.thread_Local.get();
        String absent = responseVo.getId() + "_" + redisTo.getSkuId();
        //判断信号量
        RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SESSION_CACHE_STOCK.concat(randomCode));
        boolean acquire = semaphore.tryAcquire(num);
        if (!acquire){
            return null;
        }
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(absent, num.toString(), time, TimeUnit.MILLISECONDS);
        //为false说明已经购买了
        if (!ifAbsent){
            return null;
        }
        //判断都成功后返回订单号，并发送给mq队列
        String timeId = IdWorker.getTimeId();
        SeckillCartTo seckill = new SeckillCartTo();
        seckill.setOrderSn(timeId);
        seckill.setMemberId(responseVo.getId());
        seckill.setNum(num);
        seckill.setPayAmount(redisTo.getSeckillPrice());
        seckill.setPromotionSessionId(redisTo.getPromotionSessionId());
        //TODO 发送消息给mq
        rabbitTemplate.convertAndSend(RabbitEnum.ORDER_EXCHANGE_RABBIT.getMq(),RabbitEnum.ORDER_SECKILL_ORDER.getMq(),seckill);
        return timeId;
    }

    //查询需要参与秒杀的商品信息
    @Override
    public SecKillRedisTo getSeckillSkuInfo(Long skuId) {
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SeckillConstant.SESSION_CACHE_SKUS);
        //获取所有的key
        Set<String> keys = ops.keys();
        if (keys!=null&&keys.size()>0){
            //用正则表达式匹配对应的skuId的秒杀商品信息
            String sku = skuId+"_\\d";
            for (String key : keys) {
                if (Pattern.matches(sku,key)){
                    //匹配成功，说明当前商品参与了秒杀信息
                    //取出redis中的数据
                    String s = ops.get(key);
                    //序列化
                    SecKillRedisTo redisTo = JSON.parseObject(s, SecKillRedisTo.class);
                    //查看当前时间是否在秒杀活动的时间中
                    long thisTime = System.currentTimeMillis();
                    long startTime = redisTo.getStartTime().getTime();
                    long endTime = redisTo.getEndTime().getTime();
                    if (thisTime>=startTime && thisTime<=endTime){
                        //说明处于秒杀活动的时间
                        return redisTo;
                    }
                    //没匹配到给随机码志制为空
                    redisTo.setRandomCode(null);
                    return redisTo;
                }
            }
        }
        return null;
    }

    //保存秒杀信息到redis中
    @Override
    public void upload3Day() {
        R r = couponFeignService.lates3Day();
        if (r.getCode()==0){
            //上架商品
            List<SeckillSkuVo> data = r.getData(new TypeReference<List<SeckillSkuVo>>() {});
            //缓存到redis中
            //TODO 缓存活动信息
            saveSessionInfo(data);
            //TODO 缓存商品信息
            saveSessionItem(data);
        }
    }
    //缓存活动信息
    private void saveSessionItem(List<SeckillSkuVo> data) {
        if (data!=null){
            data.stream().map(item->{
                Long startTime = item.getStartTime().getTime();
                Long endTime = item.getEndTime().getTime();
                String key = SeckillConstant.SESSION_CACHE_PREFIX + startTime + "_" + endTime;
                //判断Redis中是否有该信息，如果没有才进行添加
                if (!redisTemplate.hasKey(key)){
                    List<String> collect =
                            item.getSkuRelations().stream().map(info->{
                                String s = info.getSkuId().toString();
                                String s1 = info.getPromotionSessionId().toString();
                                return s+"_"+s1;
                            }).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key,collect);
                }
                return null;
            }).collect(Collectors.toList());
        }
    }
    //缓存商品信息
    private void saveSessionInfo(List<SeckillSkuVo> data) {
        if (!CollectionUtils.isEmpty(data)){
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SeckillConstant.SESSION_CACHE_SKUS);
            data.forEach(item->{
                SecKillRedisTo secKillRedisTo = new SecKillRedisTo();
                List<Long> collect = item.getSkuRelations().stream().map(SeckillSessionSkuVo::getSkuId).collect(Collectors.toList());
                //远程调用查询商品的信息
                R skuInfo = productFeignService.getSkuInfo(collect);
                item.getSkuRelations().stream().forEach(info->{
                    String key = info.getSkuId().toString()+"_"+info.getPromotionSessionId().toString();
                    //redis中没有缓存就存到redis中
                    if (!ops.hasKey(key)){
                        setRedis(ops, item, secKillRedisTo, skuInfo, info);
                    }
                });

            });
        }
    }

    private void setRedis(BoundHashOperations<String, Object, Object> ops, SeckillSkuVo item, SecKillRedisTo secKillRedisTo, R skuInfo, SeckillSessionSkuVo info) {
        //1、sku的商品信息
        if (skuInfo.getCode()==0){
            List<SkuInfoVo> infoData = skuInfo.getData(new TypeReference<List<SkuInfoVo>>() {});
            Map<Long, SkuInfoVo> infoVoMap =
                    infoData.stream().collect(Collectors.toMap(SkuInfoVo::getSkuId,Function.identity()));
            secKillRedisTo.setSkuInfo(infoVoMap.get(info.getSkuId()));
        }
        //2、sku的秒杀信息
        BeanUtils.copyProperties(info, secKillRedisTo);
        //3、设置当前商品的秒杀时间信息
        secKillRedisTo.setStartTime(item.getStartTime());
        secKillRedisTo.setEndTime(item.getEndTime());
        //4、设置商品的随机码（防止恶意攻击）
        String code = UUID.randomUUID().toString().replace("-", "");
        secKillRedisTo.setRandomCode(code);
        //如果当前这个场次的商品库存信息已经上架就不需要上架
        //5、使用库存作为分布式Redisson信号量（限流）
        // 使用库存作为分布式信号量
        RSemaphore semaphore = redissonClient.getSemaphore(SeckillConstant.SESSION_CACHE_STOCK+code);
        // 商品可以秒杀的数量作为信号量
        semaphore.trySetPermits(info.getSeckillCount().intValue());
        //存入redis中
        String seckell = JSON.toJSONString(secKillRedisTo);
        ops.put(info.getSkuId().toString()+"_"+ info.getPromotionSessionId().toString(),seckell);
    }
}
